<template>
    <el-container  class="container" id="top" >
        <div class="tip">
                <p>步骤：1.点击左侧需要关联的知识点，加入到知识点池内</p>
                  <p>2.选中知识池中需要关联到知识点，可上下拖动知识点调整次序（注：不要拖入选项内部）</p>
                <p>3.选中最右侧被关联到题目</p>
               <p>4.点击关联按钮，完成知识池内知识点和题目的关联</p>
              </div>
        <div class="up_content">
            
            <div class="buttonToPool">
              <el-icon><Right /></el-icon>                
            </div>
            <div class="knowledgePointPool">
              <!-- 中间的知识池 -->
         
              <span>知识点池</span>
              
              <el-tree
                ref="poolTree"
                draggable
                :data="state.PoolData"
                show-checkbox
                :props="defaultProps"
                node-key="id"
              >
              </el-tree>
              <div class="two_button">
                <el-button type="primary" size="small" @click="selectAllClick()" :icon="Select" circle ></el-button>
                <el-button type="primary" size="small" @click="deleteALLClick()" :icon="Delete" circle ></el-button>
              </div>
            </div>
            <div class="buttonToQuestionList">
              <el-button type="primary" :icon="DArrowRight" @click="linkKnowledgePointToQuestionClick">关联</el-button>
            </div>

            <div class="conciseQuestionList">
              <!-- 最右侧的题目 -->
              <span>请将左侧知识点关联到题目中</span>
              <el-table
                ref="questionListTableRef"
                :data="paperquestionData"
                style="width: 100%"                
              >
                <el-table-column type="selection" width="30" />
                <el-table-column type="index" label="序" width="40"/>
                <el-table-column label="内容" width="210" show-overflow-tooltip>
                  <template #default="scope">{{ scope.row.content_front }}</template>
                </el-table-column>                  
                <el-table-column property="knowledgepoint_cn" label="知识点" width="100" show-overflow-tooltip/>
                <el-table-column align="right" width="60" >
                  <template #header>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="取消关联"
                      placement="top"
                    >
                      <el-icon @click="cancelAllQuestionsLink()"><DeleteFilled /></el-icon>
                    </el-tooltip>
                  </template>
                  <template #default="scope"> 
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="取消关联"
                      placement="top"
                    >
                      <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="handleCancelSelectClick(scope.$index)">
                        <RemoveFilled />
                      </el-icon>
                    </el-tooltip>                    
                  </template>
                </el-table-column>
              </el-table>
            </div> 
        </div>
        <div class="two_button">
            <el-button v-if="showJustImportQuestions()" type="primary" :icon="Right" @click="submitQuestion2DatabaseClick">仅上传题目</el-button>
            <el-button type="warning" :icon="Back" @click="goBackClick" disabled>上一步</el-button>
            <el-button v-if="showImportQuestionsAndPaper()" type="primary" :icon="Right" @click="goOnkClick">上传题目和试卷</el-button>
            <el-button v-if="hasSelectPaper()" type="primary" :icon="Right" @click="supplementQuestions2PaperClick">补充题目到试卷</el-button>
            
        </div>      
    </el-container>

</template>

<script setup>
    import { reactive, ref,  onMounted, getCurrentInstance } from 'vue'
    import { useStore } from 'vuex'
    import axios from '@/utils/axios'
    import { Delete, Minus, Plus, CloseBold, Link, Select, Right, Back, DArrowRight } from '@element-plus/icons-vue'
    import { ElMessage } from 'element-plus'
    import { useRouter, useRoute } from 'vue-router'
    import { localGet, convertQuestionFormat, deleteQuestionItem, deepClone} from '@/utils'
    // 通过结构，获得appContext变量
    const { appContext } = getCurrentInstance()
    // 获得全局上下文后， 得到$bus事件总线
    const eventBus = appContext.config.globalProperties.$bus
    // 订阅本组件的事件，当tree组件的复选框被选中时，触发组件本注册的事件（把选中的数据复制到知识池中）
    eventBus.on('waitKnowledgepointTree',(data_list)=>{
        // console.log("tree传递过来的值", data_list)
        knowledgepointToPoolClick(data_list)
    })
    // （发布）触发本注册的事件:即清空tree组件选中复选框状态
    const emitToKnowledgepointTreeClearSelect=()=>{
        // ElMessage('我要清空tree中的选中状态啦！')
        eventBus.emit("waitStepTwo", [])
    }
    const router = useRouter()
    const route = useRoute()
    const knowledgepointTree=ref(null)
    const poolTree=ref(null)
    const questionListTableRef =ref(null)
    const defaultProps = {     
        label: 'name',
    }
    const store=useStore()
    let paperquestionData = reactive(store.state.paperquestionList.slice(0))
    const state = reactive({
        categoryData: [],           //左侧知识点目录
        select_knowledge_id: 0,     //忘记了
        PoolData:[],                // 知识池数据列表
        selectKnowledgepointList:[], //没有用
        importQuestionType: "",
    })
  //加载知识点
  onMounted(()=>{
    // getCategory()
    let { importQuestionType } = route.query
    state.importQuestionType = importQuestionType
    // console.log("路由名：", route.query)
    returnTop()
  })
  // 回到顶部
  const returnTop=()=>{
    document.querySelector('#top').scrollIntoView(true);    
  }
  //后台获取所有知识点
  const getCategory=()=>{
    axios.get('/knowledgepoints?size=80').then(res => {
        if (res.code==200){
            state.categoryData = res.data.results                           
        }else{
            console.log("error", res.message)      
        state.loading = false
        }
    })
    .catch((error)=>{
        console.log("error", error)
    })
  }
  //左侧选中的知识点入选到知识池
  const knowledgepointToPoolClick=(data_list)=>{
    if(data_list){
      state.PoolData=[...state.PoolData, ...data_list]  //数组的深拷贝      
    }else{
      ElMessage.error('请先选中最左侧的知识点！')      
    }
    emitToKnowledgepointTreeClearSelect([])
  }
  //删除选中的节点
  const deleteSelectClick=()=>{
    const selected = poolTree.value.getCheckedKeys(false)
    if(selected == false){
      ElMessage('请先选中知识池中的选项！')
    }else{
      for(let i=0; i<selected.length; i++){
        let element = selected[i]      
        state.PoolData = state.PoolData.filter(item => item.id != element)
      }
    }
  }
  //取消知识池的选中
  const canselSelectClick=()=>{
    poolTree.value.setCheckedKeys([], false)  
  }
  //清空知识点池
  const deleteALLClick=()=>{
    state.PoolData =[]
  }
  //全选知识池
  const selectAllClick=()=>{
    if(state.PoolData){  
      poolTree.value.setCheckedNodes(state.PoolData, false)
    }else{
      ElMessage('请先将知识点添加到知识池中！')
    }

  }
  //关联知识点到题目
  const linkKnowledgePointToQuestionClick=()=>{
    const poolTreeSelected = poolTree.value.getCheckedNodes(false)
    const questionTableSelected = questionListTableRef.value.getSelectionRows()
    if(poolTreeSelected==false ||questionTableSelected==false){
      ElMessage('请先选中知识池中的选项和题目！')
    }else{
      let length = poolTreeSelected.length
      if (length>questionTableSelected.length){
        length = questionTableSelected.length
      }
      for(let i=0;i<length;i++){
        let index = paperquestionData.indexOf(questionTableSelected[i])        
        let value_id = poolTreeSelected[i].id
        let value_name = poolTreeSelected[i].name
        const value = {id: index, value_id: value_id, value_name: value_name}
        store.commit('setQuestionListKnowledgepoint', value)
      } 
      poolTree.value.setCheckedKeys([], false)
      questionListTableRef.value.clearSelection()
    }
  }
  //检查所有题目的知识点是否都已经关联
  const verifyKnowledgepointLinkQuestion=()=>{
    let flag=true
    let index=-1
    for(let i=0;i<paperquestionData.length;i++){
      if (paperquestionData[i].knowledgepoint <=0){
        flag=false
        index=i
        break
      }
    }
    return [flag, index]
  }
  //返回上一步
  const goBackClick=()=>{
    router.push('/addPaperByFileStepOne')
  }
  //下一步,通过vuex把题目传送给第三步，即生成试卷和题目，持久化到数据库
  const goOnkClick=()=>{
    let [ flag,index ]=verifyKnowledgepointLinkQuestion()
    index++
    let s='第'+index.toString()+'题未关联知识点！'
    if (flag==false){
      ElMessage(s)
    }else{
      console.log("第二步要发送给全局状态啦", paperquestionData)
      store.commit("setQuestionListValue", paperquestionData)
      router.push('/addPaperByFileStepThree')
    }
  }
  // 仅上传题目到数据库，不生成试卷
  const submitQuestion2DatabaseClick=()=>{
    let [ flag,index ]=verifyKnowledgepointLinkQuestion()
    index++
    let s='第'+index.toString()+'题未关联知识点！'
    if (flag==false){
      ElMessage(s)
      return false
    }
    let questionList=new Array()
    console.log("提交原始题目数据：",paperquestionData)
    for(let i=0;i<paperquestionData.length;i++){
      let item={
        content:paperquestionData[i].content_front,
        answer:paperquestionData[i].answer_front,
        explain:paperquestionData[i].explain_front,
        reference:paperquestionData[i].reference,
        type:paperquestionData[i].type,
        difficulty_level:paperquestionData[i].difficulty_level,
        publish_time:paperquestionData[i].publish_time,
        open_level:"private",
        pictures:paperquestionData[i].images,
        pictures_explain:paperquestionData[i].images_explain,
        content_table:paperquestionData[i].content_table,
        explain_table:paperquestionData[i].explain_table,
        online:false,
        knowledgepoint:paperquestionData[i].knowledgepoint
      }
      questionList.push(item)
    }
    let params = { questionList: questionList, type: 'JustImportQuestions'}
    console.log('将要提交题目列表：', questionList)
    axios.post('/PersistenceManyQuestions2DatabaseAPIView/', params).then((result) => {
      if(result.code==200){
        console.log(result)
      ElMessage.success( '题目提交成功！')          
      window.location.href = "/"
      }else{
        console.log("提交错误:", result)
      }
    })
  }
  // 判断当前用户是否为管理员
  const isStaff=()=>{
    let localUser = localGet('user_information')
    return localUser.is_staff == true
  }
// 补充题目到试卷，即上传题目列表和paper_id, paper从vuex中获取
  const supplementQuestions2PaperClick=()=>{
    let [ flag,index ]=verifyKnowledgepointLinkQuestion()
    index++
    let s='第'+index.toString()+'题未关联知识点！'
    if (flag==false){
      ElMessage(s)
      return false
    }
    console.log("第2步的补充题目要被执行了")
    if(store.state.selectedPaperId <= 0){
      ElMessage("还没选中试卷！")
      return false
    }
    // 调整试题列表，去掉无关项
    let deleteList=["answer_front", "content_front","explain_front","images","images_explain","knowledgepoint_cn","type_cn","grade"]
    let uploadQuestionList=deepClone(paperquestionData)
    for(let item of uploadQuestionList){
      item=convertQuestionFormat(item)
      item=deleteQuestionItem(item,deleteList)
    }
    let params = { questionList: uploadQuestionList, type: 'importQuestionsSupplementPaper', id: store.state.selectedPaperId }    
      axios.post('/GeneratePaper2Database/', params).then((result) => {
        if(result.code==200){
          console.log("追加题目成功",result)
          ElMessage.success( '补充题目成功！')       
          store.commit('setPaperId', -1)
          if(isStaff()){
            window.location.href = "/getQuestionsByPaper"
          }else{
            window.location.href = "/getQuestionsByGenaralPaper"
          }
        }else{
          console.log("提交错误:", result)
        }
      })
  }
  // 取消该题的知识点关联,提交到vuex因为paperquestionData与vuex中的数据浅拷贝了，
  const handleCancelSelectClick=(index)=>{
    const value = {id: index, value_id: -1, value_name: "待关联"}
    store.commit('setQuestionListKnowledgepoint', value) 
  }
  // 判断补充题目按钮是否可用
  const hasSelectPaper=()=>{
    return store.state.selectedPaperId > 0
  } 
  // 判断按钮仅输入题目是否可用
  const showJustImportQuestions=()=>{
    return state.importQuestionType == 'JustImportQuestions'
  }
  // 判断按钮仅输入题目是否可用
  const showImportQuestionsAndPaper=()=>{
    return state.importQuestionType == 'importQuestionsAndPaper'
  }
</script>


<style scoped>

.container {
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  /* height: 100vh; */
}

body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
a{
  text-decoration: none;
  color: #000;
}
.up_content{
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: center;
}
.buttonToPool{
    display: flex;
    flex-direction: column;
    justify-content:space-evenly;
    border: #000;
    border-radius: 2px;
    border-style: solid;
    border-width: 1px;
}
.buttonToQuestionList{
  display: flex;
  flex-direction: column;
  justify-content: center;
  border: #000;
  border-radius: 2px;
  border-style: solid;
  border-width: 1px;
}
.knowledgePointPool{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width:200px;
  height: auto;
  border: #000;
  border-radius: 2px;
  border-style: solid;
  border-width: 1px;
  overflow: hidden;
}
.conciseQuestionList{
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: auto;
  border: #000;
  border-radius: 2px;
  border-style: solid;
  border-width: 1px;
}
.two_button{
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
}
</style>